package com.zerosky.crm.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zerosky.crm.po.ActivityAssociation;
import com.zerosky.crm.po.Branch;
import com.zerosky.crm.po.Department;
import com.zerosky.crm.po.Employee;
import com.zerosky.crm.po.OaMenu;
import com.zerosky.crm.po.OperateLog;
import com.zerosky.crm.po.Pluralize;
import com.zerosky.crm.po.Relation;
import com.zerosky.crm.po.Role;
import com.zerosky.crm.service.ActivityAssociationService;
import com.zerosky.crm.service.BranchService;
import com.zerosky.crm.service.DepartmentService;
import com.zerosky.crm.service.EmployeeService;
import com.zerosky.crm.service.MenuService;
import com.zerosky.crm.service.OperateLogService;
import com.zerosky.crm.service.PluralizeService;
import com.zerosky.crm.service.RelationService;
import com.zerosky.crm.service.RoleService;
import com.zerosky.crm.util.BaseAction;
import com.zerosky.crm.util.MD5Util;
import com.zerosky.crm.util.MyFileUploadUtils;
import com.zerosky.crm.util.PageInfo;

/**
 * 系统设置（角色、员工） 相关业务
 * 
 * @author
 *
 */
@Controller
public class SysManagerController extends BaseAction {
	private Logger logger = LoggerFactory.getLogger(SysManagerController.class); // 日志

	@Resource(name = "roleService")
	private RoleService roleService;

	@Resource(name = "menuService")
	private MenuService menuService;

	@Resource(name = "relationService")
	private RelationService relationService;

	@Resource(name = "employeeService")
	private EmployeeService employeeService;

	@Resource(name = "departmentService")
	private DepartmentService departmentService;

	@Resource(name = "branchService")
	private BranchService branchService;

	@Resource(name = "pluralizeService")
	private PluralizeService pluralizeService;

	@Resource(name = "activityAssociationService")
	private ActivityAssociationService activityAssociationService;

	@Resource(name = "operateLogService")
	private OperateLogService operateLogService;

	/**
	 * 去角色 jsp页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("toRoleJsp.do")
	public String toRoleJsp(HttpServletRequest request, HttpSession session) {
		if (checkPower(session, 60)) {
			return "WEB-INF/jsp/system/editRole";
		} else {
			return "/WEB-INF/jsp/error/404";
		}

	}
	/**
	 * 请求session是否存在
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("requestSession.do")
	@ResponseBody
	public Map<String, Object> requestSession(HttpSession session, HttpServletRequest request) {
		Map<String, Object> json = new HashMap<String, Object>();
		Employee user =(Employee) session.getAttribute("loginUser");
		if(user!=null){
			json.put("status", true);
		}else{
			json.put("status", false);
		}
		return json;
	}
	/**
	 * 角色管理查询 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("queryRole.do")
	@ResponseBody
	public Map<String, Object> queryRole(HttpSession session, HttpServletRequest request, Integer limit, Integer page,
			Integer darw, String rName) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 60)) {
			json.put("flag", "0");
			Map<String, Object> param = new HashMap<String, Object>();
			try {

				param.put("rName", rName);
				param.put("limit", limit);
				param.put("page", page);
				PageInfo<Role> pageRole = roleService.getRoleList(param);
				json.put("total", pageRole.getPageCount());
				// json.put("darw", darw+1);
				json.put("data", pageRole.getList());
				json.put("flag", "1");

			} catch (Exception e) {
				json.put("flag", "-1");
				logger.error("获取数据失败，原因：" + e);
			}
		} else {
			json.put("flag", -2);
		}
		return json;
	}

	/**
	 * AJAX 异步 添加
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("addRole.do")
	@ResponseBody
	public Map<String, Object> addRole(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			Role role) {

		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 60)) {
			json.put("data", 0);
			try {
				role.setState("0"); // 新添加进来的默认为0可用
				roleService.saveRole(role, "新增");
				json.put("data", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("data", -1);
			}
		} else {
			json.put("data", -2);
		}
		return json;
	}

	/**
	 * 编辑角色前根据id查询出角色信息
	 * 
	 * @param request
	 * @param response
	 * @param role
	 * @return
	 */
	@RequestMapping("toEditRole.do")
	@ResponseBody
	public Map<String, Object> toEditRole(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			Role role) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 60)) {
			json.put("data", 0);
			try {

				// request.setAttribute("role",
				// roleService.getRoleById(role.getId().toString()));
				json.put("data", 1);
				json.put("role", roleService.getRoleById(role.getId().toString()));

			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("data", -1);
			}
		} else {
			json.put("data", -2);
		}
		return json;

	}

	/**
	 * 编辑角色
	 * 
	 * @param request
	 * @param response
	 * @param role
	 * @return
	 */
	@RequestMapping("editRole.do")
	@ResponseBody
	public Map<String, Object> editRole(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			Role role) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 60)) {
			json.put("data", 0);
			try {
				roleService.saveRole(role, "修改");
				json.put("data", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("data", -1);
			}
		} else {
			json.put("data", -2);
		}
		return json;
	}

	/**
	 * 删除角色
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping("delRole.do")
	@ResponseBody
	public Map<String, Object> delRole(HttpSession session, HttpServletRequest request, HttpServletResponse response,
			String[] id) {

		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 60)) {
			json.put("data", 0);
			try {
				roleService.deleteRoleById(id);
				json.put("data", 1);

			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("data", -1);
			}
		} else {
			json.put("data", -2);
		}
		return json;
	}

	/**
	 * 设置权限前 展示菜单。
	 * 
	 * @return
	 */
	@RequestMapping("toAuthority.do")
	@ResponseBody
	public Map<String, Object> toAuthority(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, Integer roleId) {

		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 60)) {
			json.put("data", 0);
			try {
				List<OaMenu> menuList = menuService.getMenuList(); // 菜单列表集合
				List<Relation> relationList = relationService.getRelationByRoleIdList(roleId); // 权限集合
				json.put("menuList", menuList);
				json.put("relationList", relationList);
				json.put("roleId", roleId);
				json.put("data", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("data", -1);
			}
		} else {
			json.put("data", -2);
		}
		return json;
	}

	/**
	 * 修改权限级别
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("modifyAuthority.do")
	@ResponseBody
	public Map<String, Object> modifyAuthority(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, Integer[] menuId, Integer roleId, Integer[] parentMenuId) {
		Map<String, Object> json = new HashMap<String, Object>();
		Relation relation = new Relation();
		if (checkPower(session, 60)) {
			json.put("data", 0);
			try {

				if (roleId != null) {
					relation.setRoleId(roleId);
					relationService.deleteRelationById(roleId); // 加入权限前先删除该角色所有权限
					json.put("data", 1);
				}
				if (menuId != null && parentMenuId != null) {
					// 两个接收到的参数合并为一个数组中。
					Integer[] arr = (Integer[]) ArrayUtils.addAll(menuId, parentMenuId);
					// 循环组装好参数 放在list中
					List<Relation> list = new ArrayList<Relation>();
					for (Integer id : arr) {
						if (id == null) {
							continue;
						}
						Relation model = new Relation();
						model.setRoleId(roleId);
						model.setMenuId(id);
						list.add(model);
					}
					relationService.addRelation(list);// 插入父菜单id

					json.put("data", 1);
				}
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("data", -1);
			}
		} else {
			json.put("data", -2);
		}
		return json;
	}

	/**
	 * 去员工信息jsp
	 * 
	 * @return
	 */
	@RequestMapping("toEmployee.do")
	public String toEmployeeList(HttpSession session, HttpServletRequest request) {
		if (checkPower(session, 65)) {
			Map<String, Object> map = new HashMap<>();
			Employee user = (Employee) session.getAttribute("loginUser");
			map.put("canNotReadAllMessage", false);
			List<Department> list = new ArrayList<Department>();
			List<Department> listDept = departmentService.getDepartmentList(map);
			if (user.getQuarters().equals("8")) {
				map.put("employeeId", user.getEmployeeId());
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(map);
				for (Pluralize pluralize : pluralizeList) {
					for (Department dept : listDept) {
						if (!pluralize.getDeptId().equals(user.getDept().getDeptId())) {
							if (pluralize.getDeptId().equals(dept.getDeptId())) {
								list.add(dept);
							}
						}
					}
				}
			} else {
				Department dept = new Department();
				dept.setDeptName("-请选择分公司-");
				list.add(dept);
				for (int i = 1; i <= listDept.size(); i++) {
					list.add(listDept.get(i - 1));
				}
			}
			PageInfo<Role> roleList = roleService.getRoleList(null);
			request.setAttribute("roleList", roleList.getList());
			request.setAttribute("dept", list);
			return "WEB-INF/jsp/system/editEmployeer";
		} else {
			return "/WEB-INF/jsp/error/404";
		}
	}

	/**
	 * 员工信息分页展示
	 */
	@RequestMapping("queryEmployeeAll.do")
	@ResponseBody
	public Map<String, Object> getEmployeeList(HttpSession session, HttpServletRequest request, Integer limit,
			Integer start, Integer page, Integer darw, String empName, String deptId, String branchId, String teamId,
			Integer roleId,String empStatus) {

		Map<String, Object> json = new HashMap<String, Object>();
		PageInfo<Employee> page1 = new PageInfo<Employee>();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("limit", limit);
		param.put("page", page);
		param.put("name", empName);//名称
		param.put("deptId", deptId);//分部
		param.put("branchId", branchId);//部门
		param.put("teamId", teamId);//团队
		param.put("roleId", roleId);//角色ID
		param.put("empStatus", empStatus);//离职/在职
		if (checkPower(session, 65)) {
			try {
				page1 = employeeService.getEmployeeList(param);

				json.put("total", page1.getPageCount());
				// json.put("limit", 10);
				// json.put("page",);
				// json.put("darw", darw+1);
				json.put("data", page1.getList()); // 数据集合
				// json.put("filterCount", page1.getList());

			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
			}
		} else {
			json.put("code", -2);
		}

		return json;
	}

	/**
	 * 员工详情
	 * 
	 * @param request
	 * @param response
	 * @param empId
	 * @return
	 */
	@RequestMapping("queryEmployeeById.do")
	@ResponseBody
	public Map<String, Object> getEmployee(HttpSession session, HttpServletRequest request, String empId) {
		Employee employee = new Employee();
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 65)) {
			try {
				employee = employeeService.getEmployeeById(empId);
				json.put("roleList", roleService.getRoleList(null).getList());
				json.put("deptList", departmentService.getDepartmentList(null));
				json.put("emp", employee);
				json.put("code", 1);
			} catch (Exception e) {
				json.put("code", -1);
				logger.error("获取数据失败，原因：" + e);
			}
		} else {
			json.put("code", -2);
		}
		return json;
	}

	/**
	 * 去添加页面 查询到部门和角色两个列表
	 * 
	 * @return
	 */
	@RequestMapping("toAddEmployee.do")
	@ResponseBody
	public Map<String, Object> toAddEmployee(HttpSession session, HttpServletRequest request, String flag) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 65)) {
			try {
				json.put("roleList", roleService.getRoleList(null).getList());
				json.put("deptList", departmentService.getDepartmentList(null));
				json.put("code", 1);
			} catch (Exception e) {
				json.put("code", -1);
				logger.error("获取数据失败，原因：" + e);
			}
		} else {
			json.put("code", -2);
		}
		return json;
	}

	/**
	 * 新增员工and修改员工信息
	 * 
	 * @param request
	 * @param employee
	 * @return
	 */
	@RequestMapping("insertEmployee.do")
	@ResponseBody
	public Map<String, Object> addEmployee(HttpSession session, HttpServletRequest request, Employee employee,
			String operation, String equipment) {
		Map<String, Object> json = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();// 查询条件
		Employee user = (Employee) session.getAttribute("loginUser");
		map.put("userCard", employee.getUserCard());// 账号
		map.put("phoneNumber", employee.getPhoneNumber());// 手机号码
		if (operation != null) {
			map.put("employeeId", employee.getEmployeeId());// 手机号码
		}
		try {
			if (employeeService.checkIsExist(map) > 0) {// 验证是否存在相同账号或者手机号码
				json.put("code", -2);
				return json;
			}
			if (employee.getEmployeeId() == null) {
				employee.setEmployeeId(UUID.randomUUID().toString().replace("-", ""));
			}
			// employee.setStatus("0");
			employee.setWorkConditions("1");
			if (employee.getPassword() != null && employee.getPassword() != "") {
				employee.setPassword(MD5Util.encrypt(employee.getPassword()));
			}
			// MyFileUploadUtils.fileUpload(employee.getHotelImgFile(),
			// employee.getPicture(), "img\\", request);

			if (employee.getHotelImgFile() != null) {
				MyFileUploadUtils.saveFile(request, employee.getHotelImgFile(), "saituImage/");
				if (request.getAttribute("picture") != null || employee.getPicture() == null) {
					String picture = "saituImage/" + (String) request.getAttribute("picture");
					employee.setPicture(picture);
				}
			}

			if (operation == null) {
				/*if (!employee.getPhoneNumber().equals("")) {
					// 获取用户的的微信id
					employee.setUsersId(GOauth2Core.getWxUserId(employee.getPhoneNumber()));
				}*/
				employee.setCreateDate(new Date());
				employee.setCreatePeople(user.getName());
				employeeService.saveEmployee(employee, "新增");
			} else {
				// employee.setStatus(request.getParameter("status"));
				/*if (employee.getPhoneNumber() != null && !"pc".equals(equipment)) {
					// 获取用户的的微信id
					employee.setUsersId(GOauth2Core.getWxUserId(employee.getPhoneNumber()));
				}*/
				employee.setWorkConditions(request.getParameter("workConditions"));
				employee.setUpdateDate(new Date());
				employee.setUpdateEmpId(user.getEmployeeId());
				employeeService.saveEmployee(employee, "修改");
				if(employee.getEmployeeId().equals(user.getEmployeeId())){
					Employee emp = employeeService.getEmployeeById(user.getEmployeeId());
					session.setAttribute("loginUser", emp);
				}
			}

			json.put("code", 1);

			// 提示页面微信企业中无该员工信息
			/*if ("".equals(employee.getUsersId()) || employee.getUsersId() == null) {
				json.put("code", 2);
			}*/
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);

		}

		/*
		 * if (checkPower(session, 65)) {} else { json.put("code", -2); }
		 */

		return json;
	}

	/**
	 * 编辑用户设备码
	 * 
	 * @param request
	 * @param employee
	 * @return
	 */
	@RequestMapping("updateDevice.do")
	@ResponseBody
	public Map<String, Object> updateDevice(HttpSession session, HttpServletRequest request, Employee employee) {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Employee user = (Employee) session.getAttribute("loginUser");
			employee.setUpdateEmpId(user.getEmployeeId());
			employee.setUpdateDate(new Date());
			employeeService.saveEmployee(employee, "修改");
			json.put("code", 1);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);

		}

		/*
		 * if (checkPower(session, 65)) {} else { json.put("code", -2); }
		 */

		return json;
	}

	@RequestMapping("/delEmployee.do")
	@ResponseBody
	public Map<String, Object> delEmployeeById(HttpSession session, HttpServletRequest request, String empId) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 65)) {
			try {
				employeeService.deleteEmployeeById(empId);
				json.put("code", 1);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("code", -1);
			}
		} else {
			json.put("code", -2);
		}
		return json;

	}

	/**
	 * 编辑员工前根据id查询出
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("toModifyEmp.do")
	public String toModifyEmployee(HttpSession session, HttpServletRequest request, String id) {
		Employee emp = new Employee();
		if (checkPower(session, 65)) {
			try {
				emp = employeeService.getEmployeeById(id);
				request.setAttribute("roleList", roleService.getRoleList(null).getList());
				request.setAttribute("departmentList", departmentService.getDepartmentList(null));
				request.setAttribute("emp", emp);
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
			}
			return "WEB-INF/jsp/user/modifyEmployee";
		} else {
			return "/WEB-INF/jsp/error/404";
		}
	}

	/**
	 * 获取员工信息列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deptPhonebookList.do")
	@ResponseBody
	public Map<String, Object> deptPhonebookList(HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Employee user = (Employee) session.getAttribute("loginUser");
			List<Department> list = departmentService.getDeptPhoneBookList();
			json.put("user", user);
			json.put("data", list);
			json.put("code", 1);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 获取员工信息列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/branchPhonebookList.do")
	@ResponseBody
	public Map<String, Object> branchPhonebookList(String deptId, String oper, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			if (oper.equals("branch")) {
				map.put("deptId", deptId);
				map.put("branch", "branch");
			} else if (oper.equals("team")) {
				map.put("branchId", deptId);
			}
			Employee user = (Employee) session.getAttribute("loginUser");
			List<Branch> list = branchService.getBranchPhoneBookList(map);
			json.put("user", user);
			json.put("data", list);
			json.put("code", 1);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 根据分公司id获取下面的子部门
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getDeptIdGainBranchList.do")
	@ResponseBody
	public Map<String, Object> getDeptIdGainBranchList(String deptId, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("deptId", deptId);
			map.put("isBranch", "isBranch");
			List<Branch> list = branchService.getBranchAllList(map);
			json.put("data", list);
			json.put("code", 1);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 管理员修改用户密码
	 * 
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/changePasswordByAdmin.do")
	@ResponseBody
	public Map<String, Object> changePassword(String password, String id, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		Employee user = (Employee) session.getAttribute("loginUser");
		Employee emp = employeeService.getEmployeeById(id);
		try {
			// 加密MD5
			emp.setPassword(MD5Util.encrypt(password));
			emp.setUpdateEmpId(user.getEmployeeId());
			emp.setUpdateDate(new Date());
			employeeService.saveEmployee(emp, "修改");
			json.put("code", 1);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", 0);
		}
		return json;
	}

	/**
	 * 兼任分公司职务
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/pluralizeList.do")
	@ResponseBody
	public Map<String, Object> pluralizeList(Integer limit, Integer page, String deptName, String employeeId,
			HttpServletRequest request, HttpSession session, HttpServletResponse response) throws Exception {
		// 获取登录用户信息
		// Employee user = (Employee) session.getAttribute("loginUser");
		// 创建sql中需要的值
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> pram = new HashMap<String, Object>();
		Map<String, Object> pramAll = new HashMap<String, Object>();
		// 返回参数
		Map<String, Object> json = new HashMap<String, Object>();
		map.put("limit", limit);
		map.put("page", page);
		map.put("deptName", deptName);
		map.put("canNotReadAllMessage", false);
		pramAll.put("canNotReadAllMessage", false);
		pram.put("employeeId", employeeId);
		pram.put("pluralizeType", 3);
		try {
			List<Department> listAll = departmentService.getDepartmentList(pramAll);
			PageInfo<Department> pageInfo = departmentService.getDepartmentPageInfoList(map);
			List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(pram);
			List<Department> list = checkDepartment(pageInfo.getList(), pluralizeList);
			List<Department> userList = checkDept(listAll, pluralizeList);
			json.put("total", pageInfo.getPageCount());
			json.put("userList", userList);
			json.put("data", list);
			json.put("code", 0);

		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}
	/**
	 * 单独获取兼任分公司
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getPluralizeList.do")
	@ResponseBody
	public Map<String, Object> getPluralizeList(String employeeId,String pluralizeType,String deptId, String branchId,
			HttpServletRequest request, HttpSession session, HttpServletResponse response) throws Exception {
		// 获取登录用户信息
		// Employee user = (Employee) session.getAttribute("loginUser");
		// 创建sql中需要的值
		Map<String, Object> pram = new HashMap<String, Object>();
		Map<String, Object> pramAll = new HashMap<String, Object>();
		// 返回参数
		Map<String, Object> json = new HashMap<String, Object>();
		
		try {
			if(pluralizeType.equals("3")){
				pramAll.put("canNotReadAllMessage", false);
				pram.put("employeeId", employeeId);
				pram.put("pluralizeType", 3);
				List<Department> listAll = departmentService.getDepartmentList(pramAll);
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(pram);
				List<Department> userList = checkDept(listAll, pluralizeList);
				json.put("userList", userList);
			}else if(pluralizeType.equals("2")){
				pramAll.put("isBranch", "isBranch");
				pram.put("employeeId", employeeId);
				pram.put("pluralizeType", 2);
				List<Branch> listAll = branchService.getBranchAllList(pramAll);
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(pram);
				List<Branch> userList = checkAlreadyBranch(listAll, pluralizeList);
				json.put("userList", userList);
			}else if(pluralizeType.equals("1")){
				pramAll.put("queryByCompany", 1);
				pram.put("employeeId", employeeId);
				pram.put("pluralizeType", 1);
				List<Branch> listAll = branchService.getBranchAllList(pramAll);
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(pram);
				List<Branch> userList = checkAlreadyBranch(listAll, pluralizeList);
				json.put("userList", userList);
			}
			
			json.put("code", 0);

		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 兼任部门职务
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/pluralizeBranchList.do")
	@ResponseBody
	public Map<String, Object> pluralizeBranchList(Integer limit, Integer page, String deptName, String employeeId,
			String deptId, HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		// 获取登录用户信息
		// Employee user = (Employee) session.getAttribute("loginUser");
		// 创建sql中需要的值
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> pram = new HashMap<String, Object>();
		Map<String, Object> pramAll = new HashMap<String, Object>();// 查询全部部门的条件
		// 返回参数
		Map<String, Object> json = new HashMap<String, Object>();
		map.put("limit", limit);
		map.put("page", page);
		map.put("deptId", deptId);
		map.put("branchName", deptName);
		map.put("isBranch", "isBranch");
		pramAll.put("isBranch", "isBranch");
		pram.put("employeeId", employeeId);
		pram.put("pluralizeType", 2);
		try {
			List<Branch> listAll = branchService.getBranchAllList(pramAll);
			PageInfo<Branch> pageInfo = branchService.getBranchPageInfoList(map);
			List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(pram);
			List<Branch> list = checkBranch(pageInfo.getList(), pluralizeList);
			List<Branch> userList = checkAlreadyBranch(listAll, pluralizeList);
			json.put("total", pageInfo.getPageCount());
			json.put("userList", userList);
			json.put("data", list);
			json.put("code", 0);

		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 兼任团队职务
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/pluralizeTeamList.do")
	@ResponseBody
	public Map<String, Object> pluralizeTeamList(Integer limit, Integer page, String deptName, String employeeId,
			String deptId, String branchId, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		// 获取登录用户信息
		// Employee user = (Employee) session.getAttribute("loginUser");
		// 创建sql中需要的值
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> pram = new HashMap<String, Object>();
		Map<String, Object> pramAll = new HashMap<String, Object>();// 查询全部部门的条件
		// 返回参数
		Map<String, Object> json = new HashMap<String, Object>();
		map.put("limit", limit);
		map.put("page", page);
		map.put("branchName", deptName);
		map.put("deptId", deptId);
		map.put("pid", branchId);
		pramAll.put("queryByCompany", 1);
		pram.put("employeeId", employeeId);
		pram.put("pluralizeType", 1);
		try {
			List<Branch> listAll = branchService.getBranchAllList(pramAll);
			PageInfo<Branch> pageInfo = branchService.getBranchPageInfoList(map);
			List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(pram);
			List<Branch> list = checkBranch(pageInfo.getList(), pluralizeList);
			List<Branch> userList = checkAlreadyBranch(listAll, pluralizeList);
			json.put("total", pageInfo.getPageCount());
			json.put("userList", userList);
			json.put("data", list);
			json.put("code", 0);

		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 新增兼任
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertPluralize.do")
	@ResponseBody
	public Map<String, Object> insertPluralize(String deptId, String employeeId, Integer pluralizeType,
			HttpServletRequest request, HttpSession session, HttpServletResponse response) throws Exception {
		// 获取登录用户信息
		Employee user = (Employee) session.getAttribute("loginUser");
		// 返回参数
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Pluralize pluralize = new Pluralize();
			pluralize.setCreateDate(new Date());
			pluralize.setCreateEmployeeId(user.getEmployeeId());
			pluralize.setDeptId(deptId);
			pluralize.setEmployeeId(employeeId);
			pluralize.setPluralizeType(pluralizeType);
			if(pluralizeService.addPluralize(pluralize)>0){
				OperateLog oper=new OperateLog();
				Employee emp=employeeService.getEmployeeById(employeeId);
				if(pluralizeType==3){
					Department dept=departmentService.getDepartmentById(deptId);
					oper.setOperateContent("记录添加兼任公司操作，改动员工名称："+emp.getName()+"，隶属部门："+emp.getDept().getDeptName()+"，添加兼任分公司名称："+dept.getDeptName());
				}else if(pluralizeType==2){
					Branch branch = branchService.getBranchById(deptId);
					oper.setOperateContent("记录添加兼任公司操作，改动员工名称："+emp.getName()+"，隶属部门："+emp.getDept().getDeptName()+"，添加兼任事业部名称："+branch.getBranchName());
				}else {
					Branch branch = branchService.getBranchById(deptId);
					oper.setOperateContent("记录添加兼任公司操作，改动员工名称  ："+emp.getName()+"，隶属部门："+emp.getDept().getDeptName()+"，添加兼任团队名称："+branch.getBranchName());
				}
				oper.setDeptName(user.getDept().getDeptName());
				oper.setEmpId(user.getEmployeeId());
				oper.setEmpName(user.getName());
				oper.setOperateDate(new Date());
				oper.setOperateType("1");
				operateLogService.addOperateLog(oper);
			}
			json.put("code", 0);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 删除兼任
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deletePluralize.do")
	@ResponseBody
	public Map<String, Object> deletePluralize(String deptId,String employeeId,Integer pluralizeType, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		// 返回参数
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			// 获取登录用户信息
			Employee user = (Employee) session.getAttribute("loginUser");
			if(pluralizeService.deletePluralizeById(deptId)>0){
				Employee emp=employeeService.getEmployeeById(employeeId);
				OperateLog oper=new OperateLog();
				if(pluralizeType==3){
					Department dept=departmentService.getDepartmentById(deptId);
					oper.setOperateContent("记录取消兼任公司操作，改动员工名称："+emp.getName()+"，隶属部门："+emp.getDept().getDeptName()+"，被取消兼任部门名称："+dept.getDeptName());
				}else if(pluralizeType==2){
					Branch branch = branchService.getBranchById(deptId);
					oper.setOperateContent("记录取消兼任公司操作，改动员工名称："+emp.getName()+"，隶属部门："+emp.getDept().getDeptName()+"，被取消兼任事业部名称："+branch.getBranchName());
				}else {
					Branch branch = branchService.getBranchById(deptId);
					oper.setOperateContent("记录取消兼任公司操作，改动员工名称："+emp.getName()+"，隶属部门："+emp.getDept().getDeptName()+"，被取消兼任团队名称："+branch.getBranchName());
				}
				
				oper.setDeptName(user.getDept().getDeptName());
				oper.setEmpId(user.getEmployeeId());
				oper.setEmpName(user.getName());
				
				oper.setOperateDate(new Date());
				oper.setOperateType("1");
				operateLogService.addOperateLog(oper);
			}
			json.put("code", 0);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	// 返回兼任份公司
	private List<Department> checkDepartment(List<Department> deptList, List<Pluralize> pluralizeList) {
		for (Department dept : deptList) {
			for (Pluralize pluralize : pluralizeList) {
				if (dept.getDeptId().equals(pluralize.getDeptId())) {
					dept.setIsPluralize(1);
				}
			}
		}
		return deptList;

	}

	// 返回已兼任公司
	private List<Department> checkDept(List<Department> deptList, List<Pluralize> pluralizeList) {
		List<Department> userList = new ArrayList<Department>();
		for (Department dept : deptList) {
			for (Pluralize pluralize : pluralizeList) {
				if (dept.getDeptId().equals(pluralize.getDeptId())) {
					userList.add(dept);
				}
			}
		}
		return userList;

	}

	// 返回兼任部门或团队
	private List<Branch> checkBranch(List<Branch> deptList, List<Pluralize> pluralizeList) {
		for (Branch dept : deptList) {
			for (Pluralize pluralize : pluralizeList) {
				if (dept.getBranchId().equals(pluralize.getDeptId())) {
					dept.setIsPluralize(1);
				}
			}
		}
		return deptList;

	}

	// 返回已兼任部门或团队
	private List<Branch> checkAlreadyBranch(List<Branch> deptList, List<Pluralize> pluralizeList) {
		List<Branch> userList = new ArrayList<Branch>();
		for (Branch dept : deptList) {
			for (Pluralize pluralize : pluralizeList) {
				if (dept.getBranchId().equals(pluralize.getDeptId())) {
					userList.add(dept);
				}
			}
		}
		return userList;

	}

	/**
	 * 活动适用范围
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/activityAssociationList.do")
	@ResponseBody
	public Map<String, Object> activityAssociationList(Integer limit, Integer page, String deptId, String activityId,
			HttpServletRequest request, HttpSession session, HttpServletResponse response) throws Exception {
		// 获取登录用户信息
		// Employee user = (Employee) session.getAttribute("loginUser");
		// 创建sql中需要的值
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> pram = new HashMap<String, Object>();
		// 返回参数
		Map<String, Object> json = new HashMap<String, Object>();

		try {
			pram.put("activityId", activityId);
			List<ActivityAssociation> activityAssociationList = activityAssociationService
					.getActivityAssociationList(pram);
			map.put("limit", limit);
			map.put("page", page);
			if (deptId == null || "".equals(deptId)) {// 查询全部分公司信息
				map.put("canNotReadAllMessage", false);
				PageInfo<Department> pageInfo = departmentService.getDepartmentPageInfoList(map);
				json.put("total", pageInfo.getPageCount());
				json.put("data", checkDepartmentAndAssociation(pageInfo.getList(), activityAssociationList));
				json.put("code", 0);
			} else {// 查询某个公司下的部门
				map.put("deptId", deptId);
				map.put("isBranch", "isBranch");
				PageInfo<Branch> pageInfo = branchService.getBranchPageInfoList(map);
				json.put("total", pageInfo.getPageCount());
				json.put("data", checkBranchAndAssociation(pageInfo.getList(), activityAssociationList));
				json.put("code", 1);
			}

		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	private List<Department> checkDepartmentAndAssociation(List<Department> deptList,
			List<ActivityAssociation> activityAssociation) {
		for (Department dept : deptList) {
			for (ActivityAssociation pluralize : activityAssociation) {
				if (dept.getDeptId().equals(pluralize.getActivityScopeId())) {
					dept.setIsPluralize(1);
				}
			}
		}
		return deptList;
	}

	private List<Branch> checkBranchAndAssociation(List<Branch> deptList,
			List<ActivityAssociation> activityAssociation) {
		for (Branch dept : deptList) {
			for (ActivityAssociation pluralize : activityAssociation) {
				if (dept.getBranchId().equals(pluralize.getActivityScopeId())) {
					dept.setIsPluralize(1);
				}
			}
		}
		return deptList;
	}

	/**
	 * 新增范围
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertActivityAssociation.do")
	@ResponseBody
	public Map<String, Object> insertActivityAssociation(String activityScopeId, Integer activityId,
			HttpServletRequest request, HttpSession session, HttpServletResponse response) {
		// 获取登录用户信息
		Employee user = (Employee) session.getAttribute("loginUser");
		// 返回参数
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			ActivityAssociation pluralize = new ActivityAssociation();
			pluralize.setAssociationId(UUID.randomUUID().toString());
			pluralize.setStatus("0");
			pluralize.setCreateDate(new Date());
			pluralize.setCreateEmpId(user.getEmployeeId());
			pluralize.setActivityId(activityId);
			pluralize.setActivityScopeId(activityScopeId);
			activityAssociationService.addActivityAssociation(pluralize);
			json.put("code", 0);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 删除范围
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteActivityAssociation.do")
	@ResponseBody
	public Map<String, Object> deleteActivityAssociation(String activityId, String activityScopeId,
			HttpServletRequest request, HttpSession session, HttpServletResponse response) throws Exception {
		// 返回参数
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("activityId", activityId);
			map.put("activityScopeId", activityScopeId);
			activityAssociationService.deleteActivityAssociationById(map);
			json.put("code", 0);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 人员移动
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/staffMovement.do")
	@ResponseBody
	public Map<String, Object> staffMovement(String deptId, String branchId, String teamId, String employeeText,
			HttpServletRequest request, HttpSession session, HttpServletResponse response) throws Exception {
		// 返回参数
		Employee user = (Employee) session.getAttribute("loginUser");
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			String[] employeeList = employeeText.split(",");
			for (String employeeId : employeeList) {
				Employee emp = new Employee();
				emp.setEmployeeId(employeeId);
				if (deptId != null && deptId != "") {
					emp.setDeptId(deptId);
				}
				if (branchId != null && branchId != "" && !branchId.equals("9")) {
					emp.setBranchId(branchId);
				}
				if (teamId != null && teamId != "" && !teamId.equals("9")) {
					emp.setTeamId(teamId);
				}

				emp.setUpdateEmpId(user.getEmployeeId());
				emp.setUpdateDate(new Date());
				employeeService.saveEmployee(emp, "修改");
			}
			json.put("code", 0);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * AJAX 异步 获取分公司
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("getDeptInfo.do")
	@ResponseBody
	public Map<String, Object> getDeptInfo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Employee user = (Employee) request.getSession().getAttribute("loginUser");
			Map<String, Object> map = new HashMap<>();
			// 设置权限，如果有权限查看所有销售情况的，则有所有查看权限
			List<Department> list = new ArrayList<Department>();
			map.put("canNotReadAllMessage", false);
			List<Department> listDept = departmentService.getDepartmentList(map);
			if (user.getQuarters().equals("5") || user.getQuarters().equals("6")) {// 有管理员或董事长权限
				map.put("canNotReadAllMessage", false);
				list = departmentService.getDepartmentList(map);
			} else {// 有兼任分公司
				map.put("employeeId", user.getEmployeeId());
				map.put("pluralizeType", "3");
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(map);
				if (!user.getQuarters().equals("7") && !user.getQuarters().equals("8")) {
					list.add(user.getDept());
				}
				for (Pluralize pluralize : pluralizeList) {
					for (Department dept : listDept) {
						if (pluralize.getDeptId()!=null && !pluralize.getDeptId().equals(user.getDept().getDeptId())) {
							if (pluralize.getDeptId()!=null && pluralize.getDeptId().equals(dept.getDeptId())) {
								list.add(dept);
							}
						}
					}
				}
				if (list.size() == 0) {
					Department dept2 = new Department();
					dept2.setDeptName("-暂无数据-");
					dept2.setDeptId("99658");
					list.add(dept2);
				}
			}
			json.put("quarters", user.getQuarters());
			json.put("data", list);
			json.put("code", 0);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			e.printStackTrace();
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * AJAX 异步 获取部门
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("getBranchInfo.do")
	@ResponseBody
	public Map<String, Object> getBranchInfo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, String id) {
		Map<String, Object> json = new HashMap<String, Object>();
		Employee user = (Employee) request.getSession().getAttribute("loginUser");
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> pramAll = new HashMap<String, Object>();// 查询全部部门的条件
		List<Branch> list = new ArrayList<Branch>();
		try {
			pramAll.put("isBranch", "isBranch");
			if (user.getQuarters().equals("2") || user.getQuarters().equals("1")) {
				map.put("employeeId", user.getEmployeeId());
				map.put("pluralizeType", "2");
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(map);
				List<Branch> listAll = branchService.getBranchAllList(pramAll);

				list.add(user.getBranch());
				for (Pluralize pluralize : pluralizeList) {
					for (Branch dept : listAll) {
						if (!pluralize.getDeptId().equals(user.getBranch().getBranchId())) {
							if (pluralize.getDeptId().equals(dept.getBranchId())) {
								list.add(dept);
							}
						}
					}
				}
			} else {
				pramAll.put("deptId", id);
				list = branchService.getBranchAllList(pramAll);
			}
			json.put("quarters", user.getQuarters());
			json.put("branch", list);
			json.put("code", 0);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * AJAX 异步 获取团队
	 * 
	 * @param request
	 * @param response
	 * @return 1成功 -1异常 0失败
	 */
	@RequestMapping("getTeamInfo.do")
	@ResponseBody
	public Map<String, Object> getTeamInfo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, String id) {
		Map<String, Object> json = new HashMap<String, Object>();
		Employee user = (Employee) request.getSession().getAttribute("loginUser");
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> pramAll = new HashMap<String, Object>();// 查询全部部门的条件
		List<Branch> list = new ArrayList<Branch>();
		try {
			pramAll.put("queryByCompany", "1");
			if (user.getQuarters().equals("1")) {
				map.put("employeeId", user.getEmployeeId());
				map.put("pluralizeType", "1");
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(map);
				List<Branch> listAll = branchService.getBranchAllList(pramAll);

				list.add(user.getTeam());
				for (Pluralize pluralize : pluralizeList) {
					for (Branch dept : listAll) {
						if (!pluralize.getDeptId().equals(user.getTeam().getBranchId())) {
							if (pluralize.getDeptId().equals(dept.getBranchId())) {
								list.add(dept);
							}
						}
					}
				}
			} else {
				pramAll.put("pid", id);
				list = branchService.getBranchAllList(pramAll);
			}
			json.put("quarters", user.getQuarters());
			json.put("data", list);
			json.put("code", 0);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}
	/**
	 * 去兼任日志 jsp页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("toOperateLog.do")
	public String toOperateLog(HttpServletRequest request, HttpSession session) {
		if (checkPower(session, 112)) {
			return "WEB-INF/jsp/system/operateLog";
		} else {
			return "/WEB-INF/jsp/error/404";
		}

	}
	/**
	 * 角色管理查询 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("queryOperateLog.do")
	@ResponseBody
	public Map<String, Object> queryOperateLog(HttpSession session, HttpServletRequest request, Integer limit, Integer page,
			Integer darw, String empName,String startDate,String endDate) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (checkPower(session, 60)) {
			Map<String, Object> param = new HashMap<String, Object>();
			try {
				param.put("startDate", startDate);
				param.put("endDate", endDate);
				param.put("empName", empName);
				param.put("pageSize", limit);
				param.put("page", page);
				PageInfo<OperateLog> pageRole = operateLogService.getOperateLogList(param);
				json.put("total", pageRole.getPageCount());
				// json.put("darw", darw+1); 
				json.put("data", pageRole.getList());
				json.put("code", 0);
			} catch (Exception e) {
				e.printStackTrace();
				json.put("code", -1);
				logger.error("获取数据失败，原因：" + e);
			}
		} else {
			json.put("code", -2);
		}
		return json;
	}
	
}
